<template>
<view class="container">
    <scroll-view scroll-y="true" :style='"width:100%;height:"+sysHeight+"px"' class="area_list_blcok" :scroll-into-view="'area_'+scrollTopId" scroll-with-animation="true" enable-back-to-top="true" @scroll="handleScroll">
        <view class="current_region_block">
            <text class="current_region_title">当前区域</text>
            <view class="current_region_info">
                <view class="current_region_info_left">
                    <image src="https://image1.sansancloud.com/gongyixiangmu/2019_12/31/18/44/26_612.jpg?x-oss-process=style/preview_120" class="current_region_info_icon"></image>
                    <text class="current_region_info_text">{{locationArea}}</text>
                </view>
            </view>
        </view>
        <view class="area_list_blcok">
            <view class="area_item listGroup" v-for="(item,key) in areaList" :key="key">
                <text class="area_item_char" :id="'area_'+key">{{key}}</text>
                <view class="area_item_data" v-for="(areaItem,index) in item" :key="index" @tap="selectAreaFun(areaItem)">
                    <text class="area_item_data_text">{{areaItem.areaName}}</text>
                </view>
            </view>
        </view>
    </scroll-view>
    <!-- 导航悬浮 -->
    <view class="area_nav_bar">
        <text class="area_nav_bar_text" :style="'background: '+(currentIndex==key?setting.platformSetting.defaultColor:'')" :class="currentIndex==key?'active':''" v-for="(item,key) in areaList" :key="key" :data-id="key" @touchstart="handleTouchStart" @touchend="handleTouchEnd" @touchmove="handleTouchMove">
            {{key}}
        </text>
    </view>
    <!-- 当前字符 -->
    <view class="cur_char_blcok" v-if="hidden">
        <text>{{currentIndex}}</text>
    </view>
</view>
</template>

<script>

export default {
  data() {
    return {
      setting: null,
      loginUser: null,
      locationArea:'',
      areaList:{
          // A:[{areaName:"是"},{areaName:"的"},{areaName:"啊"},{areaName:"个"},{areaName:"饭"},{areaName:"地方"}],
          // B:[{areaName:"是"},{areaName:"的"},{areaName:"啊"}],
          // C:[{areaName:"是"},{areaName:"的"},{areaName:"啊"},{areaName:"个"}],
          // D:[{areaName:"是"},{areaName:"的"}],
          // E:[{areaName:"是"}],
          // F:[{areaName:"是"},{areaName:"的"},{areaName:"啊"},{areaName:"个"},{areaName:"饭"}],
          // G:[{areaName:"是"},{areaName:"的"},{areaName:"啊"},{areaName:"个"},{areaName:"饭"},{areaName:"地方"}],
      },
      listHeight :[],
      hidden: false, //是否隐藏当前显示中间大字母提示
      scrollTopId: '', //滚动到当前的字母城市
      currentIndex: '', //当前显示的字母index
      touches:{},
      sysHeight: 568,
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("===options===",options)
    this.setData({
      locationArea:options.location_area,
      setting: getApp().globalData.setting,
      loginUser: getApp().globalData.loginUser
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      this.setData({
          sysHeight: getApp().globalData.sysHeight
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      let that = this;
      // 触摸左侧字母表所用的数据
      that.getAllAreaFun()
      // that._calculateHeight()
      // 页面显示后计算listGroup的高度
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getAddr();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  methods: {
    selectAreaFun:function(itemData){
        console.log("===selectAreaFun===",itemData)
        let that=this;
        let params={areaId:itemData.id||0};
        that.setAreaDataFun(params);
    },
    setAreaDataFun:function(params){
        let that=this;
        var customIndex = getApp().globalData.AddClientUrl("/setLocateArea.html", params, 'post');
        wx.request({
          url: customIndex.url,
          data:customIndex.params,
          header: getApp().globalData.headerPost,
          method: 'POST',
          success: function (res) {
            console.log("=====getAllAreaFun====", res.data);
            let data = res.data.relateObj;
            if(res.data.errcode==0){
              console.log("设置成功", that.selectAddressData);
              wx.setStorageSync('selectAreaData', data);
              let pages = getCurrentPages(); //当前页面
              let prevPage = pages[pages.length - 2]; //上一页面
              console.log("====prevPage===", prevPage);
              if (prevPage) {
                prevPage.onPullDownRefresh();
              }
              wx.navigateBack({
                delta: 1
              });
            }
            wx.hideLoading();
          },
          fail: function (res) {
            wx.hideLoading();
            getApp().globalData.loadFail();
          }
        });
    },
   // 计算listGroup高度
   _calculateHeight() {
       const that = this
       let height = 0
       console.log("that.listHeight1",that.listHeight)
       this.listHeight.push(height)
       uni.createSelectorQuery().selectAll('.listGroup').boundingClientRect(function(rects){
           rects.forEach(function(rect){
               console.log("===rect==",rect)
               height += rect.height
               that.listHeight.push(height)
               console.log("that.listHeight2",that.listHeight)
           })
       }).exec()
   },
   handleTouchStart(e) {
        // 首次获取到clientY的值并记录为y1
        console.log("====e===",e);
        var y = e.touches[0].clientY;
        let touches=this.touches;
        touches.y1 = y;
        let areaList=this.areaList;
        let count=0;
        // 获取到当前的index,并记录在touches里
        for(let j in this.areaList){
            if(e.currentTarget.dataset.id==j){
                count++
            }
        }
        touches.anchorIndex = count
        // 把当前点击的字母显示在屏幕中央
        this.setData({
            hidden: true,
            touches:touches,
            scrollTopId: e.currentTarget.dataset.id,
            currentIndex: e.currentTarget.dataset.id
        })
        console.log("touches",touches)
    },
    handleTouchMove(e){
        // 滑动过程中获取当前的clientY值并记录为y2
        console.log("handleTouchMove",e)
        var y = e.touches[0].clientY;
        let scrollTopId=''
        let touches=this.touches
        touches.y2 = y
        // 根据y2-y1得到所滑动的距离除以每个字母的高度20得到字母的个数,
        // 加上第一次获取的anchorindex得到当前的序号index
        const delt = (touches.y2 - touches.y1) / 20 | 0
        let anchorIndex = touches.anchorIndex + delt
        console.log("====anchorIndex===",anchorIndex)
        console.log("touches",touches)
        let count=0
        for(let j in this.areaList){
            if(count==anchorIndex){
                console.log("==handleTouchMove--j==",j)
                scrollTopId=j
            }
            count++
        }
        // 由当前的序号index在字母表数组中找到字母并显示在屏幕中
        this.setData({
            hidden: true,
            touches:touches,
            scrollTopId: scrollTopId,
            currentIndex: scrollTopId
        })
    },
    // 触摸结束
    handleTouchEnd() {
        setTimeout(() =>{
            this.setData({
                hidden: false,
            })
        }, 0)
    },
    handleScroll(e) {
        console.log("==handleScroll==",e)
        let that=this;
        let scrollTop = e.detail.scrollTop
        const listHeight = that.listHeight
        let count=0
        // 遍历listHeight数据,如果当前的scrollTop大于height1小于height2时
        // 说明当前滚到到这个字母城市区域,获取到当前的索引i值
        for(var i=0;i<listHeight.length;i++){
            let height1 = listHeight[i]
            let height2 = listHeight[i + 1]
            if(scrollTop > height1 && scrollTop < height2){
                for(let j in that.areaList){
                    if(count==i){
                        that.setData({
                            currentIndex: j
                        })
                    }
                    count++
                }
            }
        }
    },
    getAllAreaFun:function(){
        let that = this;
        var customIndex = getApp().globalData.AddClientUrl("/list_all_area.html", {rank:1}, 'get');
        wx.request({
          url: customIndex.url,
          header: getApp().globalData.header,
          success: function (res) {
            console.log("=====getAllAreaFun====", res.data);
            let data = res.data.relateObj;
            let areaList=data;
            // for(let i=0;i<data.length;i++){
            //     if(data.rankPrefixChar){
            //         areaList[data.rankPrefixChar]=[];
            //     }else{
            //         areaList['#']=[];
            //     }
            // }
            // for(let i=0;i<data.length;i++){
            //     if(data.rankPrefixChar){
            //         areaList[data.rankPrefixChar].splice(areaList[data.rankPrefixChar].length,0,data[i])
            //     }else{
            //         areaList['#'].splice(areaList['#'].length,1,data[i])
            //     }
            // }
            console.log("areaList",areaList)
            that.setData({areaList:areaList})
            setTimeout(function(){
                that._calculateHeight()
            },3000)
            wx.hideLoading();
          },
          fail: function (res) {
            wx.hideLoading();
            getApp().globalData.loadFail();
          }
        });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>